import request from '@/utils/request'
import { setPathByOss } from '@/utils'
import { Mapping } from '@/components/CustomPage/fields/widget'

/**
 * 获取变量的key与value
 * @param varStr 变量内容
 * @param index 0：key 1:value
 * @returns {string}
 */
export function getVar(varStr = '', index = 1) {
  if (varStr) {
    const reg = /\$\{(.+?)\}/
    return varStr.match(reg)[1].split('|')[index]
  } else {
    return ''
  }
}

export default {
  props: {
    varInfo: {
      type: [Object, undefined],
      default: () => {
      }
    }
  },
  computed: {
    top() {
      return this.px2rem(this.option.top || 0)
    },
    marginBottom() {
      return this.px2rem(this.option.marginBottom || 0)
    },
    margins() {
      return this.px2rem(this.option.margins || 0)
    },
    marginsWithin() {
      return this.px2rem(this.option.marginsWithin || 0)
    },
    spacing() {
      return this.px2rem(this.option.spacing || 0)
    },
    paddingTop() {
      return this.px2rem(this.option.paddingTop || 0)
    },
    paddingRight() {
      return this.px2rem(this.option.paddingRight || 0)
    },
    paddingBottom() {
      return this.px2rem(this.option.paddingBottom || 0)
    },
    paddingTopBottom() {
      return this.px2rem(this.option.paddingTopBottom || 0)
    },
    paddingLeft() {
      return this.px2rem(this.option.paddingLeft || 0)
    },
    paddingLeftRight() {
      return this.px2rem(this.option.paddingLeftRight || 0)
    },
    _broadcast() {
      return this.broadcast()
    },
    _parameters() {
      return this.parameters()
    },
    // 图片填充方式
    imgType() {
      return this.option.imgType || 'fill'
    },
    height() {
      return this.px2rem(this.option.height || 0)
    },
    width() {
      return this.px2rem(this.option.width || 0)
    },
    isShowModuleName() {
      return this.option.isShowModuleName
    },
    // 模块名称
    moduleName() {
      return this.option.moduleName
    },
    // 模块名称
    backgroundColor() {
      return this.option.backgroundColor || '#fff'
    },
    radiusSize() {
      return this.px2rem(this.option.radiusSize || 0)
    },
    // 查看更多
    isMore() {
      return this.option.isMore || '2'
    },
    topLeftRadius() {
      return this.px2rem(this.option.topLeftRadius || 0)
    },
    topRightRadius() {
      return this.px2rem(this.option.topRightRadius || 0)
    },
    bottomLeftRadius() {
      return this.px2rem(this.option.bottomLeftRadius || 0)
    },
    bottomRightRadius() {
      return this.px2rem(this.option.bottomRightRadius || 0)
    },
    bottom() {
      return this.px2rem(this.option.bottom || 0)
    }
  },
  methods: {
    /**
         * 文字裁剪
         */
    clampText() {
      this.$nextTick(() => {
        const clampDom = document.querySelectorAll('.clamp2')
        clampDom.forEach((item) => {
          $clamp(item, { clamp: 2 })
        })
      })
    },
    /**
         * 列表样式跳转事件
         * @param item 点击的当前对象数据
         * @param field 跳转地址取 option 里的哪个字段 ,当field 为-1时，使用第三个参数
         * @param fieldObj  跳转对象
         */
    toDetail(item, field = 'link', fieldObj) {
      if (!item) return
      // 如果数据里有跳转链接，以数据里的为准
      if (item.linkAddress) {
        if (item.linkType && item.linkType === '2') {
          window.location.href = item.linkAddress
        } else {
          this.$router.push({ path: item.linkAddress })
        }
      } else {
        if (field === '-1' && fieldObj === '') {
          return
        }
        const linkData = field === '-1' ? fieldObj : this.option && this.option[field]
        if (linkData) {
          // 跳转内部链接 或自定义页面
          if (linkData.type === 'inside' || linkData.type === 'other') {
            // 判断跳转链接是否有参数，如果有参数，需要把参数获取回来，并且设置对应字段
            // 参数数组
            const paramsList = linkData.params
              ? JSON.parse(linkData.params)
              : []
            const queryObj = {}
            paramsList.forEach((x) => {
              const { keyCode, keyValue } = x
              const keyType = getVar(keyValue, 0)
              const key = getVar(keyValue)
              if (keyType === 'item') {
                queryObj[keyCode] = item[key]
              } else if (keyType === 'route') {
                queryObj[keyCode] = this.$route.query[key]
              } else if (keyType === 'self') {
                queryObj[keyCode] = this[key]
              } else {
                // 当前组件上的某个变量上的值
                queryObj[keyCode] = this[keyType][key]
              }
            })
            this.$router.push({ path: linkData.link, query: queryObj })
          } else if (linkData.type === 'outside') {
            window.location.href = linkData.link
          }
        }
      }
    },
    /**
         * 查看更多跳转事件
         */
    toMore(path) {
      if (path) {
        if (path.startsWith('http')) {
          window.location.href = path
        } else {
          this.$router.push({ path: path })
        }
      }
    },
    /**
         * 统一设置图片展示地址
         * @param fileUrl
         * @param fileUrl4oss
         * @returns {string|*}
         */
    setImgPath(fileUrl, fileUrl4oss,) {
      return setPathByOss(fileUrl, fileUrl4oss)
    },
    px2rem(px) {
      return (px && (px / 75) * 1 + 'rem') || ''
    },
    /**
         * 获取参数
         * @param paramsList
         * @param type refresh: 取刷新的变量
         * @returns {{}|*}
         */
    getParams(paramsList = [], type) {
      if (paramsList.length) {
        return paramsList.reduce((obj, item) => {
          if (item.paramType === '1') {
            obj[item.key] = item.fixedParam
          } else {
            // 从组件关联变量中获取
            // refresh  是关联组件引发操作， selfUpdate是组件自身刷新或者加载更多
            if ((type === 'refresh' || type === 'selfUpdate') && item.compVar) {
              if (getVar(item.compVar, 0) === 'route') {
                // obj[item.key] = this.$route.query[getVar(item.dynamicParam)]
                obj[item.key] = this.varInfo[item.compVar]
              } else if (getVar(item.compVar, 0) === 'self') {
                obj[item.key] = this[getVar(item.compVar, 1)]
              }
            } else {
              // 从变量初始值中取
              if (getVar(item.dynamicParam, 0) === 'route') {
                // obj[item.key] = this.$route.query[getVar(item.dynamicParam)]
                obj[item.key] = this.varInfo[item.dynamicParam]
              } else if (getVar(item.dynamicParam, 0) === 'self') {
                obj[item.key] = this[getVar(item.dynamicParam, 1)]
              }
            }
          }
          return obj
        }, {})
      } else {
        return {}
      }
    },
    /**
         * 通过接口获取数据
         * @returns {Promise<unknown>}
         */
    getData(arr = [], type) {
      if (arr.length > 0) {
        const data = arr.map((item, index) => {
          return new Promise((resolve, reject) => {
            const paramsObj = item.params
            request({
              url: item.link,
              method: 'post',
              data: {
                ...this.getParams(paramsObj, type)
              }
            })
              .then((res) => {
                const result = res.data
                res.data['dynamicConfigCode'] = item.configCode
                resolve(result)
              })
              .catch((err) => {
                reject(err)
              })
          })
        })
        return new Promise((resolve, reject) => {
          Promise.all(data)
            .then((res) => {
              if (res && Array.isArray(res) && res.length) {
                const result = {}
                res.forEach((item) => {
                  const code = item.dynamicConfigCode
                  Reflect.deleteProperty(item, 'dynamicConfigCode')
                  result[code] = item
                })
                resolve(result)
              }
            })
            .catch((err) => {
              resolve('error')
            })
        })
      }
    },
    /**
         * 给组件变量赋值
         */
    setVarValue() {
      if (this?.option?.compVar && Array.isArray(this?.option?.compVar)) {
        this.option.compVar.forEach((item) => {
          let value = item.value === undefined ? '' : item.value
          const key = getVar(item.code, 1)
          if (getVar(item.code, 0) === 'self') {
            if (value === '' && this[key] !== '') {
              value = this[key]
            }

            // 设置初始值，如果组件变量是需要从路由中获取的，则需要从页面变量中获取到并赋值

            if (value && (typeof value === 'string') && value.indexOf('|') > -1) {
              if (getVar(value, 0) === 'route') {
                const pageValue = this.varInfo[value]
                this.$set(this, getVar(item.code, 1), pageValue)
              }
            } else { // 组件变量的值是 一个输入的值
              this.$set(this, getVar(item.code, 1), value)
            }
          }
        })
      }
    },
    /**
         * 获取数据
         * @returns {Promise<unknown>}
         */
    initData() {
      return new Promise(async(resolve, reject) => {
        this.setVarValue()
        if (this?.option?.dataorigin === '1') {
          if (this.setData && typeof this.setData === 'function') {
            this.setData(this?.option?.fixedData || {})
          }
          resolve()
        } else if (
                    this?.option?.dataorigin === '2' &&
                    this.option.dynamicData
        ) {
          const result = await this.getData(this.option.dynamicData)
          if (this.setData && typeof this.setData === 'function') {
            this.setData(result)
          }
          resolve()
        } else {
          reject({ msg: '配置错误！' })
        }
      })
    },

    /**
         * 组件关联，发生变化时，进行赋值
         * @param relateDom
         * @param relateMap
         */
    varAssignment(relateDom, relateMap) {
      try {
        if (relateDom && relateMap) {
          const map = JSON.parse(relateMap) || []
          map.forEach((item) => {
            const otherVarValue = relateDom[getVar(item.leftVar)]
            if (getVar(item.rightVar, 0) !== 'route') {
              this.$set(this, getVar(item.rightVar), otherVarValue)
            }
          })
        }
      } catch (err) {
        console.warn(err)
      }
    },
    async refresh(relateDom, relateMap) {
      this.varAssignment(relateDom, relateMap)
      // 判断组件本身刷新的时候是否还有其他操作，先执行其他操作后再掉接口
      if (this.refresh4other && typeof this.refresh4other === 'function') {
        await this.refresh4other()
      }
      const result = await this.getData(this.option.dynamicData, 'refresh')
      if (this.setData && typeof this.setData === 'function') {
        this.setData(result)
      }
    },
    /**
         * 通过code去调用对应接口
         * */
    async getDataByCode(code) {
      return new Promise(async(resolve, reject) => {
        const arr = this.option.dynamicData.filter((item) => {
          return item.configCode === code
        })
        const result = await this.getData(arr, 'selfUpdate')
        this.setData(result)
        resolve()
      })
    },
    /**
         * 获取所有的标签
         * */
    getLabelList() {
      if (this.option?.ActivityLabel?.length > 0) {
        const data = this.option.ActivityLabel.map((item, index) => {
          return new Promise((resolve, reject) => {
            request({
              url: '/API-ENTERPRISE-APP/app/labelInfos/queryByCode',
              method: 'post',
              data: {
                classifyCode: item.type,
                id: 'SAAS'
              }
            })
              .then((res) => {
                const result = res.data
                res.data['flagCode'] = item.type
                resolve(result)
              })
              .catch((err) => {
                reject(err)
              })
          })
        })
        return new Promise((resolve, reject) => {
          Promise.all(data)
            .then((res) => {
              if (res && Array.isArray(res) && res.length) {
                const result = {}
                res.forEach((item) => {
                  const code = item.flagCode
                  Reflect.deleteProperty(item, 'flagCode')
                  result[code] = item.code === '200' && item.data && item.data.length ? item.data : []
                })
                resolve(result)
              }
            })
            .catch((err) => {
              resolve('error')
            })
        })
      }
    },
    /**
         * 设置标签
         * */
    setLabel(list, name) {
      list.forEach((l) => {
        l.labelList = []
        const currentLabelInfo = {
          name: '',
          style: '',
          showType: ''
        }
        const labelList = this.option.ActivityLabel.map((item) => {
          const currentLabelTypeInfo = this.labelObj[item.type].find(
            (t) => t.hitParam == l[item.key]
          )
          currentLabelInfo.name = currentLabelTypeInfo?.name || ''
          currentLabelInfo.style =
                        (currentLabelTypeInfo?.labelConfig &&
                            JSON.parse(currentLabelTypeInfo?.labelConfig)) ||
                        {}
          currentLabelInfo.showType = currentLabelTypeInfo?.showType || ''
          return {
            ...item,
            ...currentLabelInfo
          }
        })
        labelList.forEach((item) => {
          if (l.labelList.length === 0) {
            l.labelList.push(item)
          } else {
            l.labelList.forEach((ite) => {
              if (!(ite.position && ite.position === item.position)) {
                l.labelList.push(item)
              }
            })
          }
        })
      })
      this.$set(this, name, list)
    },
    /** 获取映射关系
         * data：数据源，field：标识
         * */
    getMapping(data, field) {
      const map = this.option.mapping || []
      const newField = map.find(item => {
        return field === item.code
      })
      if (newField !== undefined && newField.value !== '') {
        return data[newField.value]
      } else {
        return data[field]
      }
    }
  }
}
